package com.yylending.las.authority.register;

import android.Manifest;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.content.Loader;
import android.text.InputType;
import android.text.TextUtils;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.*;
import butterknife.*;
import cn.jpush.android.api.JPushInterface;
import com.tbruyelle.rxpermissions.Permission;
import com.trello.rxlifecycle.components.support.RxAppCompatActivity;
import com.yyfax.common.tools.RegexUtil;
import com.yyfax.infrastructure.PermissionsGrantedHelper;
import com.yyfax.infrastructure.mvp.Presenter;
import com.yyfax.infrastructure.mvp.PresenterLoader;
import com.yylending.las.*;
import com.yylending.las.R;
import com.yylending.las.authority.login.LoginActivity;
import com.yylending.las.authority.login.LoginPresenter;
import com.yylending.las.authority.verifycode.VerifyCodeModel;
import com.yylending.las.authority.verifycode.VerifyCodePresenter;
import com.yylending.las.base.BaseActivity;
import com.yylending.las.common.location.LocationPresenter;
import com.yylending.las.common.location.entity.Location;
import com.yylending.las.common.utils.CountDownTimerUtils;
import com.yyfax.infrastructure.statistics.StatService;
import com.yylending.las.common.utils.PermissionUtil;
import com.yylending.las.common.widgets.CommonDialog;
import com.yylending.las.webview.WebViewActivity;

/**
 * Created by HenryZhang on 2016/10/25.
 * Copyright © 2016 www.yyfax.com. All Rights Reserved.
 * 注册账号界面
 */
public class RegistActivity extends BaseActivity implements VerifyCodePresenter.View, RegisterPresenter.View, LoginPresenter.View, LocationPresenter.View {

	private static final int REQUEST_CODE_GPS = 100;
	private final static int LOADER_ID_VERIFY_CODE = 1;
	private final static int LOADER_ID_REGISTER = 2;
	private final static int LOADER_ID_LOGIN = 3;
	private final static int LOADER_ID_LOCATE = 4;
	private static final String TAG = RegistActivity.class.getSimpleName();

	@BindView(R.id.register_delete_phone)
	ImageView mDeletePhoneNum;
	@BindView(R.id.register_phone_number)
	EditText mPhoneNumberTx;
	@BindView(R.id.register_password)
	EditText mPasswordTx;
	@BindView(R.id.register_delete_pwd)
	ImageView mDeletePwd;
	@BindView(R.id.register_verification_code)
	EditText mVerificationCode;
	@BindView(R.id.register_time_down_tx)
	TextView mTimeDownTx;
	@BindView(R.id.register_delete_verification_code)
	ImageView mDeleteVerification;
	@BindView(R.id.register_submit_btn)
	Button mSubmitBtn;
	@BindView(R.id.register_user_deal_chb)
	CheckBox mUserDealChb;

	private String mPhoneNum;
	private String mPassword;
	/**
	 * 验证码
	 */
	private String mCode;
	private CountDownTimerUtils mCountDownTimer;

	private VerifyCodePresenter mVerifyCodePresenter;
	private RegisterPresenter mRegisterPresenter;
	private LoginPresenter mLoginPresenter;
	private LocationPresenter mLocatePresenter;

	private Location mLocation;
	/**
	 * 是否在定位成功之后自动注册
	 */
	private boolean mAutoRegister = false;

	@Override
	public void onLoadFinished(Loader<Presenter> loader, Presenter data, int placeholder) {
		switch (loader.getId()) {
			case LOADER_ID_VERIFY_CODE:
				mVerifyCodePresenter = (VerifyCodePresenter) data;
				mVerifyCodePresenter.attach(this);
				break;
			case LOADER_ID_REGISTER:
				mRegisterPresenter = (RegisterPresenter) data;
				mRegisterPresenter.attach(this);
				break;
			case LOADER_ID_LOGIN:
				mLoginPresenter = (LoginPresenter) data;
				mLoginPresenter.attach(this);
				break;
			case LOADER_ID_LOCATE:
				mLocatePresenter = (LocationPresenter) data;
				mLocatePresenter.attach(this);
				PermissionsGrantedHelper.PermissionsEachGranted(mRxPermissions, mGrantedListener, Manifest.permission.ACCESS_COARSE_LOCATION);
				break;
		}
	}

	@Override
	public Loader<Presenter> onCreateLoader(int id, Bundle args) {
		switch (id) {
			case LOADER_ID_VERIFY_CODE:
				return new PresenterLoader<>(this, new VerifyCodePresenter.Generator());
			case LOADER_ID_REGISTER:
				return new PresenterLoader<>(this, new RegisterPresenter.Generator());
			case LOADER_ID_LOGIN:
				return new PresenterLoader<>(this, new LoginPresenter.Generator());
			case LOADER_ID_LOCATE:
				return new PresenterLoader<>(this, new LocationPresenter.Generator());
		}
		return null;
	}

	public static void start(RxAppCompatActivity aty, int requestCode) {
		Intent intent = new Intent(aty, RegistActivity.class);
		aty.startActivityForResult(intent, requestCode);
	}

	@Override
	protected void onResume() {
		super.onResume();
	}

	@Override
	protected void onStart() {
		super.onStart();
		Global.setThirdPartyPageOpenedFlag(false);
	}

	@Override
	protected void onStop() {
		super.onStop();
	}

	@Override
	protected void onDestroy() {
		cancelTimer();
		getSupportLoaderManager().destroyLoader(LOADER_ID_VERIFY_CODE);
		getSupportLoaderManager().destroyLoader(LOADER_ID_REGISTER);
		getSupportLoaderManager().destroyLoader(LOADER_ID_LOGIN);
		getSupportLoaderManager().destroyLoader(LOADER_ID_LOCATE);
		super.onDestroy();
	}

	private void cancelTimer() {
		if (mCountDownTimer != null) {
			mCountDownTimer.cancel();
		}
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_regist);
		ButterKnife.bind(this);
		setTopBarVisible(false);
		getSupportLoaderManager().initLoader(LOADER_ID_VERIFY_CODE, null, this);
		getSupportLoaderManager().initLoader(LOADER_ID_REGISTER, null, this);
		getSupportLoaderManager().initLoader(LOADER_ID_LOGIN, null, this);
		getSupportLoaderManager().initLoader(LOADER_ID_LOCATE, null, this);
	}

	@OnCheckedChanged(R.id.password_visible_chb)
	public void onPasswordChecked(CompoundButton btn, boolean checked) {
		if(checked){
			mPasswordTx.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
		}else{
			mPasswordTx.setTransformationMethod(PasswordTransformationMethod.getInstance());
		}
		mPasswordTx.setSelection(mPasswordTx.getText().length());//设置光标到最末尾
	}

	@OnTextChanged(value = R.id.register_verification_code, callback = OnTextChanged.Callback.TEXT_CHANGED)
	public void onVerifyCodeChanged(CharSequence s, int start, int before, int count) {
		if (s.length() != 0) {
			mDeleteVerification.setVisibility(View.VISIBLE);
		} else {
			mDeleteVerification.setVisibility(View.GONE);
		}
	}

	@OnTextChanged(value = R.id.register_password, callback = OnTextChanged.Callback.TEXT_CHANGED)
	public void onPasswordChanged(CharSequence s, int start, int before, int count) {
		if (s.length() != 0) {
			mDeletePwd.setVisibility(View.VISIBLE);
		} else {
			mDeletePwd.setVisibility(View.GONE);
		}
	}

	@OnTextChanged(value = R.id.register_phone_number, callback = OnTextChanged.Callback.TEXT_CHANGED)
	public void onPhoneNumberChanged(CharSequence s, int start, int before, int count) {
		mPhoneNum = mPhoneNumberTx.getText().toString().trim();
		if (mPhoneNum.length() != 0) {
			mDeletePhoneNum.setVisibility(View.VISIBLE);
		} else {
			mDeletePhoneNum.setVisibility(View.GONE);
		}
	}

	/**
	 * 处理点击注册逻辑
	 */
	private boolean checkRegister() {
		boolean rs = false;
		mPhoneNum = mPhoneNumberTx.getText().toString().trim();
		mPassword = mPasswordTx.getText().toString().trim();
		mCode = mVerificationCode.getText().toString().trim();
		if (TextUtils.isEmpty(mPhoneNum)) {
			showToast(getString(R.string.please_input_toast, getString(R.string.mobile_phone)));
		} else if (TextUtils.isEmpty(mPassword)) {
			showToast(getString(R.string.please_input_toast, getString(R.string.password)));
		} else if (TextUtils.isEmpty(mCode)) {
			showToast(getString(R.string.please_input_toast, getString(R.string.verification_code)));
		} else if (mPhoneNum.length() < 11) {//手机是否正确
			showToast(R.string.input_correct_phone);
		} else if (mPassword.length() < 6 || !RegexUtil.isRightPwd(mPassword)) {    //判断密码格式是否正确
			showToast(R.string.please_set_right_password);
		} else {
			rs = true;
		}
		return rs;
	}

	//点击事件
	@OnClick({R.id.register_back_ic, R.id.register_have_id, R.id.register_delete_phone, R.id.register_time_down_tx, R.id.register_submit_btn,
			R.id.register_user_deal_chb, R.id.register_user_deal, R.id.register_delete_pwd, R.id.register_delete_verification_code})
	public void onViewClicked(View view) {
		switch (view.getId()) {
			case R.id.register_back_ic://返回按钮
				finish();
				break;
			case R.id.register_have_id://已有账号去登录
				LoginActivity.start(this);
				finish();
				break;
			case R.id.register_delete_phone://删除号码
				mPhoneNumberTx.getText().clear();
				break;
			case R.id.register_time_down_tx://获取验证码
				mPhoneNum = mPhoneNumberTx.getText().toString().trim();
				if (TextUtils.isEmpty(mPhoneNum)) {
					showToast(getString(R.string.please_input_toast, getString(R.string.mobile_phone)));
					break;
				}
				Boolean isCorrectNum = (mPhoneNum.length() < 11);//RegularExpress.isMobileNumber(mPhoneNum);
				if (!isCorrectNum) {
					mTimeDownTx.setEnabled(false);
					showLoading(true);
					mVerifyCodePresenter.verificationCode(VerifyCodeModel.TYPE_TEXT, mPhoneNum, VerifyCodeModel.OPERATION_REGISTER, "60");
				} else {
					showToast(R.string.input_correct_phone);
				}
				break;
			case R.id.register_submit_btn://确定注册
				mSubmitBtn.setEnabled(false);
				YJKD.hideInputWindow(this);
				if (checkRegister()) {
					showLoading(true);
					mAutoRegister = false;
					register();
				}else{
					mSubmitBtn.setEnabled(true);
				}
				break;
			case R.id.register_user_deal_chb://是否同意用户协议
				mSubmitBtn.setEnabled(mUserDealChb.isChecked());
				break;
			case R.id.register_user_deal://跳转到用户协议
				if (!TextUtils.isEmpty(Global.LOGIN_REGISTER_PROTOCOL_URL)) {
					WebViewActivity.start(this, Global.BASE_URL + Global.LOGIN_REGISTER_PROTOCOL_URL, getString(R.string.user_agreement_link), -1);
				}
				break;
			case R.id.register_delete_pwd:
				mPasswordTx.getText().clear();
				break;
			case R.id.register_delete_verification_code:
				mVerificationCode.getText().clear();
				break;
			default:
				break;
		}
	}

	@Override
	public void loginSuccess() {
		if(!TextUtils.isEmpty(Global.LOGIN_USER_ID)){
			JPushInterface.setAlias(getApplicationContext(), 1, Global.LOGIN_USER_ID);
		}
		dismissLoading();
		setResult(RESULT_OK);
		finish();
	}

	@Override
	public void loginFail(String msg) {
		mSubmitBtn.setEnabled(true);
		dismissLoading();
	}

	@Override
	public void loginRetCode(String retCode) {
	}

	@Override
	public void registerSuccess() {
		if (null == mLocation) {
			mLoginPresenter.login(mPhoneNum, mPassword, null, null);
		} else {
			mLoginPresenter.login(mPhoneNum, mPassword, String.valueOf(mLocation.longitude), String.valueOf(mLocation.latitude));
		}
	}

	@Override
	public void registerFail(String code, String msg) {
		mSubmitBtn.setEnabled(true);
		dismissLoading();
		showToast(msg);
		//验证码不正确时清空验证码
		if(Constants.CODE_100007.equals(code)) mVerificationCode.setText("");
	}

	@Override
	public void registerRetCode(String retCode) {
		StatService.onEventWithSingleAttribute(this, StatIDSet.EVENT_ID_REGISTER,retCode);
	}

	@Override
	public void getVerifyCodeSuccess(String code) {
		dismissLoading();
		showLongToast(R.string.validate_code_sent);
		mCountDownTimer = new CountDownTimerUtils(mTimeDownTx, 60000, 1000, getString(R.string.get_verification_code_again), getString(R.string.retry_count_down));
		mCountDownTimer.start();
	}

	@Override
	public void getVerifyCodeFail(String msg) {
		dismissLoading();
		if (TextUtils.isEmpty(msg)) {
			showToast(R.string.validate_code_send_fail);
		} else {
			showLongToast(msg);
		}
		mTimeDownTx.setEnabled(true);
	}

	@Override
	public void onFunctionalError(Throwable e, boolean autoTips, int functionalCode) {
		super.onFunctionalError(e, autoTips, functionalCode);
		switch (functionalCode) {
			case VerifyCodeModel.METHOD_GET_VERIFY_CODE:
				runOnUiThread(new Runnable() {
					@Override
					public void run() {
						mTimeDownTx.setEnabled(true);
					}
				});
				break;
			case RegisterModel.METHOD_REGISTER:
				mSubmitBtn.setEnabled(true);
				break;
		}
	}

	@Override
	public void onLocateSuccess(Location location) {
		mLocation = location;
		if (mAutoRegister)
			register();
	}

	@Override
	public void onLocateFail(boolean noPermission) {
		if (mAutoRegister) {
			dismissLoading();
			showToast(R.string.locate_need_retry);
			mAutoRegister = false;
		}
	}

	@Override
	public void showDialog() {

	}

	@Override
	public void dismissDialog() {

	}

	private void register() {
		if (null == mLocation) {
			mRegisterPresenter.register(mCode, mPhoneNum, mPassword, null, null);
		} else {
			mRegisterPresenter.register(mCode, mPhoneNum, mPassword, String.valueOf(mLocation.longitude), String.valueOf(mLocation.latitude));
		}
	}

	private PermissionsGrantedHelper.PermissionsGrantedListener mGrantedListener = new PermissionsGrantedHelper.PermissionsGrantedListener() {
		@Override
		public void permissionsEachGrantedResult(Permission permission) {
			switch (permission.name) {
				case Manifest.permission.ACCESS_COARSE_LOCATION:
					if (permission.granted) {
						mLocatePresenter.startLocation(false);
					} else {
						if (mAutoRegister)
							dismissLoading();
					}
					break;
				default:
					break;
			}
		}

		@Override
		public void PermissionsAllGrantedResult(boolean granted, int requestCode) {

		}
	};
}